<template>
	<view class="login-page">
		
		<view class="login-logo" :style="{'background-image': 'url('+ loginBg + ')'}">
			<!-- <view class="set" @click="handleSet">设置</view> -->
			<view class="logo">
				<text class="word">{{ systemName }}</text>
			</view>
		</view>

		<!-- 登录表单 -->
		<view class="login-box">
			<view class="login-form">
				<view class="form-item">
					<i></i>
					<view class="form-input">
						<input v-model='form.username' type="text" :placeholder="$t('system.login.username')" @input="clearInput">
						<uni-icons class="clear-icon" type="clear" size="22" color="#c0c0c0" v-if="showClearIcon" @click="clearIcon"></uni-icons>
					</view>
				</view>
				<view class="form-item">
					<i></i>
					<view class="form-input">
					    <input v-model='form.password' :placeholder="$t('system.login.password')" :password="showPassword" />
					    <view class="pwd-img" @click="changePassword">
							<image :src="!showPassword ? pwdShow : pwdHidden" />
						</view>
					</view>
				</view>
				<view class="form-item" v-if="enabledValidCode">
					<i></i>
					<view class="form-input">
					    <input v-model='form.captcha' :placeholder="$t('system.login.code')" />
					    <view class="code-img" @click="refreshCode">
							<image :src="code.src" />
						</view>
					</view>
				</view>
				<view class="form-item item-end">
					<view class="form-checkbox">
						<checkbox-group @change="rememberPwd">
							<label>
								<checkbox value="Y" :checked="rememberPassword == 'Y' ? true : false" />{{$t('app.login.rememberPassword')}}
							</label>
						</checkbox-group>
					</view>
				</view>
			</view>
			
			<view>
				<button class="login-btn" type="primary" @click="handleLogin">{{logining ? $t('app.login.loggingIn') : $t('system.login.logIn')}}</button>
			</view>
			
			<view class="error" v-if="errorMessage && errorMessage.length">
				<span style="color: #f44;">{{errorMessage}}</span>
			</view>
		</view>
		
		<view class="more-btn" v-if="openOffline">
			<text @click="toOffline">{{$t('app.login.offlineMode')}}</text>
			<text @click="toRemind" v-if="showRemind" style="margin-left: 10px;">{{$t('app.login.authExpiration')}}</text>
		</view>
		
		<u-modal v-model="showSet" ref="uModal" :title="$t('app.login.interfaceSettings')" :show-cancel-button="true" :async-close="true" @confirm="confirmSet">
			<view class="slot-content">
				<u-form class="login-set">
					<u-form-item :label="$t('app.login.serviceIPAddress')" label-width="160">
						<u-input v-model="server.baseIp" :placeholder="$t('baseCommon.message.pleaseEnter', { title: $t('app.login.serviceIPAddress') })"/>
					</u-form-item>
					<u-form-item :label="$t('app.login.servicePortNumber')" label-width="160">
						<u-input v-model="server.basePort" type="number" :placeholder="$t('baseCommon.message.pleaseEnter', { title: $t('app.login.servicePortNumber') })"/>
					</u-form-item>
					<u-form-item :label="$t('app.login.reportIPAddress')" label-width="160">
						<u-input v-model="server.reportIp" :placeholder="$t('baseCommon.message.pleaseEnter', { title: $t('app.login.reportIPAddress') })"/>
					</u-form-item>
					<u-form-item :label="$t('app.login.reportPortNumber')" label-width="160">
						<u-input v-model="server.reportPort" type="number" :placeholder="$t('baseCommon.message.pleaseEnter', { title: $t('app.login.reportPortNumber') })"/>
					</u-form-item>
				</u-form>
			</view>
		</u-modal>
		
	</view>
</template>

<script>
	import pwdHidden from '../../../static/images/login/pwd-hidden.png'
	import pwdShow from '../../../static/images/login/pwd-show.png'
	import config from '@/utils/config/index.js'
	import { getCaptcha, validateLogin, login, loginSSO, authorize, accessToken, getUserInfoByName } from '@/api/platform/oauth.js'
	import { getAppResource, findCurrentUserSubSystem, queryBindInfo, bindPushUser, updateBindStatus, updateReadStatus, getByMobileSn, getLicenseMsg } from '@/api/platform/common.js'
	import { notice, utilities } from '@/utils/common.js'
	import { getInstIdFormData } from '@/api/base/flow.js'
	import { getSerialNo, blueToothRestart } from '@/utils/device.js'
	
	export default {
	    data () {
	        return {
				pwdHidden,
				pwdShow,
				form: {
					username: '',
					password: '',
					requestId: '',
					captcha: '',
				},
				showClearIcon: false,
				showPassword: true,
	            errorMessage: '',
	            logining: false,
				enabledValidCode: false,
				code: {
					src: '',
					value: '',
					len: 5,
					type: 'src'
				},
				server: {
					baseIp: '',
					basePort: '',
					reportIp: '',
					reportPort: ''
				},
				showSet: false,
				type: '',
				msgData: {},
				snFlag: true,
				rememberPassword: '',
				showRemind: false,
				remindData: []
	        }
	    },
		computed: {
			loginBg() {
				return utilities.getConfig('PROJECT').LOGIN_BACKGROUND
			},
			systemName() {
				return utilities.getConfig('PROJECT').SYSTEM_NAME
			},
			openOffline() {
				return utilities.getConfig('PROJECT').OPEN_OFFLINE
			},
			openPush() {
				return utilities.getConfig('PROJECT').OPEN_PUSH
			},
			openSSO() {
				return utilities.getConfig('PROJECT').OPEN_SSO
			},
			useBlueTooth() {
				return utilities.getConfig('PROJECT').USE_BLUETOOTH
			},
			checkSn() {
				return utilities.getConfig('PROJECT').CHECK_SN
			}
		},
		onLoad(option) {
			this.form.username = uni.getStorageSync("userAccount")
			
			this.type = option.type ? option.type : ''
			this.msgData = option.msgData ? JSON.parse(option.msgData) : {}
			
			this.init(true)
		},
		onShow() {
			if(this.useBlueTooth) {
				// 关闭传感器连接
				uni.closeBluetoothAdapter({
					success(res) {
						console.log('关闭蓝牙模块:' + res);
						uni.removeStorageSync("bindSensor")
					}
				})
			}
			
			// 记住密码
			let rememberPassword = uni.getStorageSync("rememberPassword")
			if(!rememberPassword) {
				this.rememberPassword = 'Y'
				uni.setStorageSync("rememberPassword", this.rememberPassword)
			} else{
				this.rememberPassword = rememberPassword
			}
			this.form.password = this.rememberPassword == 'Y' ? uni.getStorageSync("password") : ''
			
			// 微服务到期提醒
			getLicenseMsg().then(res => {
				if(res.data && res.data.length > 0) {
					this.showRemind = true
					this.remindData = res.data
				}
			})
		},
	    methods: {
			init(isBackfill) {
				// let baseUrl = config.baseUrl.substring(config.baseUrl.indexOf("/") + 2, config.baseUrl.lastIndexOf("/"))
				// let reportUrl = config.reportUrl.substring(config.reportUrl.indexOf("/") + 2, config.reportUrl.lastIndexOf("/"))
				// this.server.baseIp = uni.getStorageSync("baseIp") ? uni.getStorageSync("baseIp") : baseUrl.split(":")[0]
				// this.server.basePort = uni.getStorageSync("basePort") ? uni.getStorageSync("basePort") : baseUrl.split(":")[1]
				// this.server.reportIp = uni.getStorageSync("reportIp") ? uni.getStorageSync("reportIp") : reportUrl.split(":")[0]
				// this.server.reportPort = uni.getStorageSync("reportPort") ? uni.getStorageSync("reportPort") : reportUrl.split(":")[1]
				
				const params = {
					requestId: this.form.requestId
				}
				getCaptcha(params).then(res=>{
					if (res.data) {
						this.enabledValidCode = true
						this.code.src = res.data
						this.form.requestId = res.variables.requestId
					} else {
						this.enabledValidCode = false
					}
					if (isBackfill) {
						this.form.code = this.code.value
					}
				})
				
				// #ifdef APP-PLUS
				// 获取设备序列号
				uni.setStorageSync("serialNo", getSerialNo())
				// 重启蓝牙
				if(this.useBlueTooth) {
					// blueToothRestart()
					uni.removeStorageSync('bindSensor')
				}
				// #endif
				
				// if(this.checkSn) {
				// 	getByMobileSn(uni.getStorageSync("serialNo")).then(res => {
				// 		if(!res.data) {
				// 			this.snFlag = false
				// 		}
				// 		// 如果是定制机，并且使用了蓝牙，重启蓝牙(商用机重启蓝牙需要申请权限)
				// 		// #ifdef APP-PLUS
				// 		if(res.data.mobileType === 0 && this.useBlueTooth) {
				// 			// 重启蓝牙
				// 			blueToothRestart()
				// 		}
				// 		// #endif
				// 	})
				// }
			},
			handleSet() {
				this.showSet = true
			},
			confirmSet() {
				if (!this.server.baseIp || !this.server.baseIp.length) {
					this.$refs.uModal.clearLoading();
				    notice.toast(this.$t('baseCommon.message.pleaseEnter', { title: this.$t('app.login.serviceIPAddress') }))
					return
				}
				if (!this.server.basePort || !this.server.basePort.length) {
					this.$refs.uModal.clearLoading();
					notice.toast(this.$t('baseCommon.message.pleaseEnter', { title: this.$t('app.login.servicePortNumber') }))
					return
				}
				if (!this.server.reportIp || !this.server.reportIp.length) {
					this.$refs.uModal.clearLoading();
				    notice.toast(this.$t('baseCommon.message.pleaseEnter', { title: this.$t('app.login.reportIPAddress') }))
					return
				}
				if (!this.server.reportPort || !this.server.reportPort.length) {
					this.$refs.uModal.clearLoading();
					notice.toast(this.$t('baseCommon.message.pleaseEnter', { title: this.$t('app.login.reportPortNumber') }))
					return
				}
				
				// setTimeout(() => {
				// 	uni.setStorageSync("baseIp", this.server.baseIp)
				// 	uni.setStorageSync("basePort", this.server.basePort)
				// 	uni.setStorageSync("reportIp", this.server.reportIp)
				// 	uni.setStorageSync("reportPort", this.server.reportPort)
				// 	uni.setStorageSync("baseUrl", "http://" + this.server.baseIp + ":" + this.server.basePort + "/ibps")
				// 	uni.setStorageSync("reportUrl", "http://" + this.server.reportIp + ":" + this.server.reportPort + "/raqsoft")
					
				// 	this.showSet = false;
				// }, 1000)
			},
			refreshCode() {
				this.init()
			},
			clearInput(event) {
			    if (event.detail.value.length > 0) {
			        this.showClearIcon = true;
			    } else {
			        this.showClearIcon = false;
			    }
			},
			clearIcon() {
			    this.form.username = '';
			    this.showClearIcon = false;
			},
			changePassword() {
			    this.showPassword = !this.showPassword;
			},
	        async handleLogin() {
				if(!this.snFlag) {
					notice.toast(this.$t('app.login.withoutAuthorization'))
					return
				}
	            if (this.logining) { 
	                return
	            }
	            this.errorMessage = ''
	            if (!this.form.username || !this.form.username.length) {
	                this.errorMessage = this.$t('system.login.username')
	                return
	            }
	            if (!this.form.password || !this.form.password.length) {
	                this.errorMessage = this.$t('system.login.password')
	                return
	            }
				if (this.enabledValidCode) {
					if (!this.form.captcha || !this.form.captcha.length) {
					    this.errorMessage = this.$t('system.login.code')
						return
					}
				}
				
				// 登录验证开启
				if(this.openSSO) {
					if(!await this.validateLogin()) {
						notice.toast(this.$t('app.login.loginFailedNoUser'))
						return
					}
				}
				
				uni.showLoading({
					title: this.$t('app.login.loggingIn'), 
					mask: true,
				})
	            // this.logining = true
				const params = {
					captcha: this.form.captcha,
					password: this.form.password,
					requestId: this.form.requestId,
					username: this.form.username
				}
				let loginRes
				if(this.openSSO) {
					loginRes = await loginSSO(params)
				} else {
					loginRes = await login(params)
				}
				authorize(loginRes.data).then(res => {
					const param = {
						authorize_code: res.data,
						client_id: config.APP_CLIENT_ID,
						client_secret: config.APP_CLIENT_SECRET,
						grant_type: config.APP_GRANT_TYPE
					}
					accessToken(param).then(res => {
						let token = res.data.access_token
						if (token.length) {
							uni.setStorageSync("_app_token", token);
							
							// 获取用户信息
							getUserInfoByName(this.form.username).then(async res => {
								if(res){
									uni.setStorageSync("userMobile", res.data.user.mobile);
									uni.setStorageSync("userOrgId", res.data.org ? res.data.org.id : "");
									uni.setStorageSync("userOrgName", res.data.org ? res.data.org.name : "");
									uni.setStorageSync("userId", res.data.user.userId ? res.data.user.userId : res.data.user.id);
									uni.setStorageSync("userName", res.data.user.name);
									uni.setStorageSync("userFullName", res.data.user.fullname);
									uni.setStorageSync("userAccount", this.form.username);
									uni.setStorageSync("password", this.form.password);
									
									// 获取用户子系统
									await findCurrentUserSubSystem().then(res => {
										if(!res.data) {
											notice.toast(this.$t('app.login.noPermissionToSystem'))
											throw new Error(this.$t('app.login.noPermissionToSystem'))
										}
									})
									
									// 获取菜单信息
									await getAppResource().then(res=>{
										const listData = res.data.filter(item => {
											return item.id !== '0'
										})
										let menuList = utilities.transformToTreeFormat(listData, {
											idKey: 'id',
											parentIdKey: 'parentId',
											childrenKey: 'children'
										})
										uni.setStorageSync("menuList", menuList)
									})
									
									// #ifdef APP-PLUS
									// 消息推送
									if(this.openPush) {
										await this.handlePushUser()
									}
									// #endif
								}
							})
							.then(() => {
								uni.hideLoading()
								this.logining = false
								if(this.type) { // 离线消息跳转
									getInstIdFormData(this.msgData.bizKey).then(res=>{
										let opinionList = res.data.attributes.opinionList
										let taskId = opinionList[opinionList.length-1].taskId
										let url = res.data.formModel.mobileValue
										let nodeId = res.data.attributes.nodeId
										
										uni.navigateTo({
											url: url + "&type=approve&taskId=" + taskId + "&nodeId=" + nodeId + "&sourceType=" + this.type
										})
									})
									// 将消息更新为已读
									let param = {
										messageId: this.msgData.messageId,
										isReaded: 'Y'
									}
									updateReadStatus(param)
								} else { //正常登录
									uni.switchTab({
										url: '/pages/platform/home/index'
									})
								}
							})
						}
					})
				})
	        },
			// 登录验证
			async validateLogin() {
				let params = {
					userName: 'user0', // this.form.username,
					password: 'Rdkx@123456' // this.form.password
				}
				let res = await validateLogin(params)
				if(!res.result) {
					return false
				}
				return true
			},
			handlePushUser() {
				let userId = uni.getStorageSync("userId")
				let cid = plus.push.getClientInfo().clientid
				queryBindInfo().then(res=>{
					if(res.data) {
						let original = res.data.clientId
						// 已绑定CID与当前不一致
						if(original != cid) {
							let that = this
							uni.showModal({
							    title: this.$t('baseCommon.message.tips'),
							    content: this.$t('app.login.haveBoundReplace'),
							    success: function (res) {
							        if (res.confirm) {
										// 绑定用户
							            that.bindPushUser()
										
										// 更新绑定状态
										const params = {
											userId: userId,
											clientId: original,
											bindStatus: "0"
										}
										updateBindStatus(params)
							        } else if (res.cancel) {
							            
							        }
							    }
							});
						}
					} else {
						this.bindPushUser()
					}
				})
			},
			bindPushUser() {
				// 获取系统信息
				let device = uni.getSystemInfoSync();
				const params = {
					userId: uni.getStorageSync("userId"),
					userName: uni.getStorageSync("userName"),
					clientId: plus.push.getClientInfo().clientid,
					userAlias: "",
					userType: "0",
					phoneDevice: device.platform,
					phoneBand: device.brand,
					phoneModel: device.model,
					createTime: utilities.getNowDateTime(),
					bindStatus: "1",
					updateUser: uni.getStorageSync("userId"),
					updateTime: utilities.getNowDateTime()
				}
				// 绑定用户
				bindPushUser(params)
			},
			toOffline() {
				uni.navigateTo({
					url: '/pages/business/inspect/offline/index'
				})
			},
			rememberPwd(e) {
				this.rememberPassword = e.detail.value[0]
				if(e.detail.value.length === 0) {
					this.rememberPassword = "N"
				}
				uni.setStorageSync("rememberPassword", this.rememberPassword)
			},
			toRemind() {
				uni.navigateTo({
					url: '/pages/base/service-expiration?data=' + encodeURIComponent(JSON.stringify(this.remindData))
				})
			}
	    }
	}
</script>

<style lang="scss" scoped>
	.login-page {
	    position: fixed;
	    top: 0;
	    bottom: 0;
	    left: 0;
	    right: 0;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	
	.login-logo {
		width: 100%;
		height: 40%;
		background-size: 100% 100%;
	}
	
	.logo {
		width: 100%; 
		margin-top: 25%;
		text-align: center;
	}
	
	.word {
		font-size: 40px;
		font-weight: bolder;
		color: #FFFFFF;
		letter-spacing: 5px;
		text-shadow: #999 3px 4px 5px;
	}
	
	.set {
	    float: right;
	    margin: 10px;
		padding-top: var(--status-bar-height);
	    color: #fff;
		font-size: 16px;
	}
	
	.login-box {
		width: 80%; 
		margin: 0 10%;
		margin-top: 10px;
	}
	
	.login-form {
		padding: 0 30px;
		display: flex;
		flex-direction: column;
	}
	
	.form-item {
		display: flex;
		height: 45px;
	}
	
	.form-item i {
		width: 30px;
		height: 60px;
	}
	
	.form-item:nth-of-type(1) i { 
		background: url(../../../static/images/login/login-user.png) center no-repeat;
		background-size: 100%;
	}
	
	.form-item:nth-of-type(2) i { 
		background: url(../../../static/images/login/login-pwd.png) center no-repeat; 
		background-size: 100%;
	}
	
	.form-item:nth-of-type(3) i {
		background: url(../../../static/images/login/login-code.png) center no-repeat; 
		background-size: 100%;
	}
	
	.form-item input { 
		width: 100%;
		font-size: 14px;
		padding: 8px 0;
	}
	
	.form-input {
		display: flex; 
		border-bottom: 1px solid #ddd;
		margin: 10px 0 0 10px;
		width: calc(100% - 40px);
	}
	
	.clear-icon {
	    padding-top: 8px;
	}
	
	.login-btn { 
		background: #1E91E6; 
		border-radius: 50px; 
		width: 100%;
		height: 50px; 
		margin-top: 20px; 
		box-shadow:0px 5px 10px rgba(0, 0, 0, 0.35);
	}
	
	.error {
	    margin: 5px 0 0 20px;
	}
	
	.pwd-img {
	    padding-top: 8px;
	}
	
	.pwd-img image{
	    width: 24px;
	    height: 20px;
	}
	
	.code-img image{
	    width: 90px;
	    height: 30px;
	}
	
	.login-set {
		/* background-color: #fff; */
		margin: 0 10px;
	}
	
	.more-btn {
		position: fixed;
		bottom: 10px;
		color: #1E91E6;
	}
	
	.item-end {
		justify-content: flex-end;
	}
	
	.form-checkbox {
		margin-top: 20px;
		color: grey;
		font-size: 14px;
		
		checkbox {
			transform: scale(0.7);
		}
	}
</style>
